package com.shuorikeji.huohuo.utils;

import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FontManager {
    private static final Map<String, Typeface> fontCache = new HashMap<>();

    public static Typeface getTypeface(Context context, String fontPath) {
        if (fontCache.containsKey(fontPath)) {
            return fontCache.get(fontPath);
        }

        Typeface typeface;
        try {
            if (fontPath.startsWith("http")) {
                return null; // 需要先下载
            } else if (fontPath.startsWith("/")) {
                typeface = Typeface.createFromFile(fontPath);
            } else {
                typeface = Typeface.createFromAsset(context.getAssets(), fontPath);
            }
            fontCache.put(fontPath, typeface);
            return typeface;
        } catch (Exception e) {
            Log.e("wxl", "加载字体失败: " + fontPath, e);
            return Typeface.DEFAULT;
        }
    }

    public static List<File> getDownloadedFonts(Context context) {
        File fontDir = new File(context.getExternalFilesDir(null), "book_fonts");
        if (!fontDir.exists()) return Collections.emptyList();

        File[] files = fontDir.listFiles(file ->
                file.getName().toLowerCase().endsWith(".ttf") ||
                        file.getName().toLowerCase().endsWith(".otf"));

        return files != null ? Arrays.asList(files) : Collections.emptyList();
    }

    public static void clearFontCache() {
        fontCache.clear();
    }
}
